#!/bin/bash
# ----------------------------------------------------------------------
# neds handy rotating-filesystem-snapshot utility: weekly snapshots
# ----------------------------------------------------------------------
# intended to be run weekly as a cron job 
# ----------------------------------------------------------------------

unset PATH

# ------------- system commands used by this script --------------------
ID=/usr/bin/id;
ECHO=/bin/echo;

MOUNT=/bin/mount;
RM=/bin/rm;
MV=/bin/mv;
CP=/bin/cp;

RSYNC=/usr/bin/rsync;

SSH=/usr/bin/ssh;
# ------------- file locations -----------------------------------------

SNAPSHOT_RW=/data/veni_backups;  # backup directory on msl

BACKUP_DIR=/var/www/twiki;  # directory to backup

BACKUP=msl;  # server to backup to


# ------------- the script itself --------------------------------------

# make sure we're running as root
if (( `$ID -u` != 0 )); then { $ECHO "Sorry, must be root.  Exiting..."; exit; } fi

# attempt to chmod the directory to RW; else abort
$SSH $BACKUP chmod 600 $SNAPSHOT_RW ;
if (( $? )); then
{
	$ECHO "snapshot: could not chmod $SNAPSHOT_RW readwrite";
	exit;
}
fi;


# step 1: delete the oldest snapshot, if it exists:
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/weekly.3 ] ; then			\
$RM -rf $SNAPSHOT_RW/weekly.3 ;				\
fi ;"

# step 2: move the snapshots
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/weekly.2 ] ; then			\
mv $SNAPSHOT_RW/weekly.2 $SNAPSHOT_RW/weekly.3 ;				\
fi ;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/weekly.1 ] ; then			\
mv $SNAPSHOT_RW/weekly.1 $SNAPSHOT_RW/weekly.2 ;				\
fi ;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/weekly.0 ] ; then			\
mv $SNAPSHOT_RW/weekly.0 $SNAPSHOT_RW/weekly.1 ;				\
fi ;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.6 ] ; then			\
$CP -al $SNAPSHOT_RW/daily.6 $SNAPSHOT_RW/weekly.0 ;				\
fi ;"


# now remount the directory as readonly

$SSH $BACKUP chmod 400 $SNAPSHOT_RW ;
if (( $? )); then
{
	$ECHO "snapshot: could not chmod $SNAPSHOT_RW readonly";
	exit;
} fi;
